<template>
  <div class="patient-treatment">
    <h1>Patient Treatment</h1>
    
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="patient-card">
          <template #header>
            <div class="card-header">
              <span>Patient Information</span>
              <el-button v-if="patientInfo.id" type="primary" link @click="selectDifferentPatient">
                Change Patient
              </el-button>
            </div>
          </template>
          
          <div v-if="!patientInfo.id" class="select-patient">
            <el-input
              v-model="searchQuery"
              placeholder="Search patient by name or ID"
              prefix-icon="el-icon-search"
              clearable
              @input="searchPatients"
            />
            
            <el-table
              v-if="searchResults.length > 0"
              :data="searchResults"
              style="width: 100%; margin-top: 15px;"
              @row-click="selectPatient"
              highlight-current-row
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="Name" />
              <el-table-column width="80">
                <template #default="scope">
                  <el-button type="primary" link @click.stop="selectPatient(scope.row)">
                    Select
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <el-empty v-else-if="searchQuery" description="No matching patients" />
            <el-empty v-else description="Search for a patient" />
          </div>
          
          <div v-else class="patient-info">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="Patient ID">{{ patientInfo.id }}</el-descriptions-item>
              <el-descriptions-item label="Name">{{ patientInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="Gender">{{ patientInfo.gender === 1 ? 'Male' : 'Female' }}</el-descriptions-item>
              <el-descriptions-item label="Date of Birth">{{ formatDate(patientInfo.birthDate) }}</el-descriptions-item>
              <el-descriptions-item label="Phone">{{ patientInfo.phone }}</el-descriptions-item>
              <el-descriptions-item label="Email">{{ patientInfo.email }}</el-descriptions-item>
            </el-descriptions>
            
            <div class="patient-actions" style="margin-top: 15px;">
              <el-button type="primary" plain @click="viewMedicalHistory">
                View Medical History
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-card v-if="patientInfo.id" class="treatment-card">
          <template #header>
            <div class="card-header">
              <span>Treatment Information</span>
            </div>
          </template>
          
          <el-form ref="treatmentForm" :model="treatmentForm" :rules="rules" label-width="120px">
            <el-form-item label="Diagnosis" prop="diagnosis">
              <el-input v-model="treatmentForm.diagnosis" type="textarea" :rows="2" />
            </el-form-item>
            
            <el-form-item label="Treatment" prop="treatment">
              <el-input v-model="treatmentForm.treatment" type="textarea" :rows="3" />
            </el-form-item>
            
            <el-divider content-position="left">Medications</el-divider>
            
            <div v-for="(drug, index) in treatmentForm.drugs" :key="index" class="drug-item">
              <el-row :gutter="10">
                <el-col :span="10">
                  <el-form-item 
                    :label="index === 0 ? 'Drug' : ''" 
                    :prop="'drugs.' + index + '.drug'"
                    :rules="{ required: true, message: 'Please select a drug', trigger: 'change' }"
                  >
                    <el-select 
                      v-model="drug.drug" 
                      filterable 
                      placeholder="Select drug"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in drugOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                
                <el-col :span="5">
                  <el-form-item 
                    :label="index === 0 ? 'Quantity' : ''" 
                    :prop="'drugs.' + index + '.quantity'"
                    :rules="{ required: true, message: 'Please enter quantity', trigger: 'blur' }"
                  >
                    <el-input-number 
                      v-model="drug.quantity" 
                      :min="1" 
                      controls-position="right"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                
                <el-col :span="7">
                  <el-form-item 
                    :label="index === 0 ? 'Usage' : ''" 
                    :prop="'drugs.' + index + '.usage'"
                    :rules="{ required: true, message: 'Please enter usage', trigger: 'blur' }"
                  >
                    <el-input v-model="drug.usage" placeholder="e.g. 3 times daily" />
                  </el-form-item>
                </el-col>
                
                <el-col :span="2" style="display: flex; align-items: flex-end;">
                  <el-button 
                    v-if="index === 0"
                    type="primary" 
                    icon="el-icon-plus" 
                    circle 
                    @click="addDrug"
                    style="margin-bottom: 20px;"
                  >+</el-button>
                  <el-button 
                    v-else
                    type="danger" 
                    icon="el-icon-delete" 
                    circle 
                    @click="removeDrug(index)"
                    style="margin-bottom: 20px;"
                  >-</el-button>
                </el-col>
              </el-row>
            </div>
            
            <el-divider content-position="left">Medical Checks</el-divider>
            
            <div v-for="(check, index) in treatmentForm.checks" :key="index" class="check-item">
              <el-row :gutter="10">
                <el-col :span="15">
                  <el-form-item 
                    :label="index === 0 ? 'Check' : ''" 
                    :prop="'checks.' + index + '.check'"
                    :rules="{ required: true, message: 'Please select a check', trigger: 'change' }"
                  >
                    <el-select 
                      v-model="check.check" 
                      filterable 
                      placeholder="Select medical check"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in checkOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                
                <el-col :span="7">
                  <el-form-item 
                    :label="index === 0 ? 'Note' : ''" 
                    :prop="'checks.' + index + '.note'"
                  >
                    <el-input v-model="check.note" placeholder="Optional note" />
                  </el-form-item>
                </el-col>
                
                <el-col :span="2" style="display: flex; align-items: flex-end;">
                  <el-button 
                    v-if="index === 0"
                    type="primary" 
                    icon="el-icon-plus" 
                    circle 
                    @click="addCheck"
                    style="margin-bottom: 20px;"
                  >+</el-button>
                  <el-button 
                    v-else
                    type="danger" 
                    icon="el-icon-delete" 
                    circle 
                    @click="removeCheck(index)"
                    style="margin-bottom: 20px;"
                  >-</el-button>
                </el-col>
              </el-row>
            </div>
            
            <el-form-item label="Notes" prop="notes">
              <el-input v-model="treatmentForm.notes" type="textarea" :rows="2" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="submitTreatment">Submit Treatment</el-button>
              <el-button @click="resetForm">Reset</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <el-card v-else class="empty-treatment-card">
          <el-empty description="Please select a patient to start treatment" />
        </el-card>
      </el-col>
    </el-row>
    
    <!-- Medical History Dialog -->
    <el-dialog
      v-model="historyDialogVisible"
      title="Medical History"
      width="70%"
    >
      <el-tabs v-model="activeHistoryTab">
        <el-tab-pane label="Treatments" name="treatments">
          <el-table :data="treatmentHistory" style="width: 100%">
            <el-table-column prop="date" label="Date" width="120">
              <template #default="scope">
                {{ formatDate(scope.row.date) }}
              </template>
            </el-table-column>
            <el-table-column prop="doctor" label="Doctor" width="150" />
            <el-table-column prop="diagnosis" label="Diagnosis" />
            <el-table-column prop="treatment" label="Treatment" />
            <el-table-column width="80">
              <template #default="scope">
                <el-button type="primary" link @click="viewTreatmentDetail(scope.row)">
                  Details
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="Medications" name="medications">
          <el-table :data="medicationHistory" style="width: 100%">
            <el-table-column prop="date" label="Date" width="120">
              <template #default="scope">
                {{ formatDate(scope.row.date) }}
              </template>
            </el-table-column>
            <el-table-column prop="doctor" label="Doctor" width="150" />
            <el-table-column prop="drug" label="Medication" />
            <el-table-column prop="quantity" label="Quantity" width="100" />
            <el-table-column prop="usage" label="Usage" />
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="Medical Checks" name="checks">
          <el-table :data="checksHistory" style="width: 100%">
            <el-table-column prop="date" label="Date" width="120">
              <template #default="scope">
                {{ formatDate(scope.row.date) }}
              </template>
            </el-table-column>
            <el-table-column prop="doctor" label="Doctor" width="150" />
            <el-table-column prop="check" label="Check" />
            <el-table-column prop="result" label="Result" />
            <el-table-column prop="note" label="Note" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    
    <!-- Treatment Detail Dialog -->
    <el-dialog
      v-model="treatmentDetailDialogVisible"
      title="Treatment Details"
      width="50%"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="Date">{{ formatDate(selectedTreatment.date) }}</el-descriptions-item>
        <el-descriptions-item label="Doctor">{{ selectedTreatment.doctor }}</el-descriptions-item>
        <el-descriptions-item label="Diagnosis">{{ selectedTreatment.diagnosis }}</el-descriptions-item>
        <el-descriptions-item label="Treatment">{{ selectedTreatment.treatment }}</el-descriptions-item>
        <el-descriptions-item label="Notes">{{ selectedTreatment.notes }}</el-descriptions-item>
      </el-descriptions>
      
      <div v-if="selectedTreatment.drugs && selectedTreatment.drugs.length" style="margin-top: 20px;">
        <h3>Medications</h3>
        <el-table :data="selectedTreatment.drugs" style="width: 100%">
          <el-table-column prop="drug" label="Drug" />
          <el-table-column prop="quantity" label="Quantity" width="100" />
          <el-table-column prop="usage" label="Usage" />
        </el-table>
      </div>
      
      <div v-if="selectedTreatment.checks && selectedTreatment.checks.length" style="margin-top: 20px;">
        <h3>Medical Checks</h3>
        <el-table :data="selectedTreatment.checks" style="width: 100%">
          <el-table-column prop="check" label="Check" />
          <el-table-column prop="note" label="Note" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { useDrugStore } from '../../stores/drug'
import { useCheckStore } from '../../stores/checks'
import { useOrderStore } from '../../stores/orders'

const route = useRoute()
const router = useRouter()
const drugStore = useDrugStore()
const checkStore = useCheckStore()
const orderStore = useOrderStore()

// Patient selection
const searchQuery = ref('')
const searchResults = ref([])
const patientInfo = ref({})

// Form
const treatmentForm = ref({
  diagnosis: '',
  treatment: '',
  drugs: [{ drug: null, quantity: 1, usage: '' }],
  checks: [{ check: null, note: '' }],
  notes: ''
})
const treatmentFormRef = ref(null)

// Options
const drugOptions = ref([])
const checkOptions = ref([])

// Dialogs
const historyDialogVisible = ref(false)
const activeHistoryTab = ref('treatments')
const treatmentDetailDialogVisible = ref(false)
const selectedTreatment = ref({})

// History data
const treatmentHistory = ref([])
const medicationHistory = ref([])
const checksHistory = ref([])

// Form rules
const rules = {
  diagnosis: [
    { required: true, message: 'Please enter diagnosis', trigger: 'blur' }
  ],
  treatment: [
    { required: true, message: 'Please enter treatment', trigger: 'blur' }
  ]
}

// Mock data for development
const mockPatients = [
  { id: 'P001', name: 'John Doe', gender: 1, birthDate: '1980-05-15', phone: '123-456-7890', email: 'john@example.com' },
  { id: 'P002', name: 'Jane Smith', gender: 0, birthDate: '1985-10-20', phone: '234-567-8901', email: 'jane@example.com' },
  { id: 'P003', name: 'Robert Johnson', gender: 1, birthDate: '1975-03-08', phone: '345-678-9012', email: 'robert@example.com' }
]

const mockDrugs = [
  { id: 1, name: 'Amoxicillin 500mg', type: 'Prescription' },
  { id: 2, name: 'Ibuprofen 200mg', type: 'OTC' },
  { id: 3, name: 'Atorvastatin 10mg', type: 'Prescription' },
  { id: 4, name: 'Lisinopril 10mg', type: 'Prescription' }
]

const mockChecks = [
  { id: 1, name: 'Complete Blood Count', type: 'Blood Test' },
  { id: 2, name: 'Chest X-Ray', type: 'Imaging' },
  { id: 3, name: 'ECG', type: 'Physical' },
  { id: 4, name: 'Urinalysis', type: 'Blood Test' }
]

const mockTreatmentHistory = [
  { 
    id: 1, 
    date: '2025-03-20', 
    doctor: 'Dr. Smith', 
    diagnosis: 'Upper respiratory infection', 
    treatment: 'Rest, fluids, and antibiotics',
    notes: 'Follow up in 7 days if symptoms persist',
    drugs: [
      { drug: 'Amoxicillin 500mg', quantity: 20, usage: '1 tablet twice daily' },
      { drug: 'Ibuprofen 200mg', quantity: 15, usage: '1-2 tablets as needed for pain or fever' }
    ],
    checks: [
      { check: 'Complete Blood Count', note: 'Check for infection markers' }
    ]
  },
  { 
    id: 2, 
    date: '2025-01-15', 
    doctor: 'Dr. Johnson', 
    diagnosis: 'Hypertension', 
    treatment: 'Medication and lifestyle changes',
    notes: 'Reduce sodium intake, exercise regularly'
  }
]

onMounted(async () => {
  // In a real app, you would fetch data from the API
  drugOptions.value = mockDrugs
  checkOptions.value = mockChecks
  
  // Check if patientId is provided in the route query
  const patientId = route.query.patientId
  if (patientId) {
    const patient = mockPatients.find(p => p.id === patientId)
    if (patient) {
      patientInfo.value = patient
    }
  }
})

// Watch for search query changes
watch(searchQuery, (newVal) => {
  if (newVal) {
    searchPatients()
  } else {
    searchResults.value = []
  }
})

function searchPatients() {
  if (!searchQuery.value) {
    searchResults.value = []
    return
  }
  
  const query = searchQuery.value.toLowerCase()
  searchResults.value = mockPatients.filter(patient => 
    patient.id.toLowerCase().includes(query) || 
    patient.name.toLowerCase().includes(query)
  )
}

function selectPatient(patient) {
  patientInfo.value = patient
  searchQuery.value = ''
  searchResults.value = []
}

function selectDifferentPatient() {
  patientInfo.value = {}
}

function formatDate(dateString) {
  return dayjs(dateString).format('YYYY-MM-DD')
}

function addDrug() {
  treatmentForm.value.drugs.push({ drug: null, quantity: 1, usage: '' })
}

function removeDrug(index) {
  treatmentForm.value.drugs.splice(index, 1)
}

function addCheck() {
  treatmentForm.value.checks.push({ check: null, note: '' })
}

function removeCheck(index) {
  treatmentForm.value.checks.splice(index, 1)
}

function viewMedicalHistory() {
  // In a real app, you would fetch the patient's medical history
  treatmentHistory.value = mockTreatmentHistory
  
  // Extract medication history from treatments
  medicationHistory.value = []
  treatmentHistory.value.forEach(treatment => {
    if (treatment.drugs && treatment.drugs.length) {
      treatment.drugs.forEach(drug => {
        medicationHistory.value.push({
          date: treatment.date,
          doctor: treatment.doctor,
          drug: drug.drug,
          quantity: drug.quantity,
          usage: drug.usage
        })
      })
    }
  })
  
  // Extract checks history from treatments
  checksHistory.value = []
  treatmentHistory.value.forEach(treatment => {
    if (treatment.checks && treatment.checks.length) {
      treatment.checks.forEach(check => {
        checksHistory.value.push({
          date: treatment.date,
          doctor: treatment.doctor,
          check: check.check,
          result: 'Normal', // Mock result
          note: check.note
        })
      })
    }
  })
  
  historyDialogVisible.value = true
}

function viewTreatmentDetail(treatment) {
  selectedTreatment.value = treatment
  treatmentDetailDialogVisible.value = true
}

async function submitTreatment() {
  if (!treatmentFormRef.value) return
  
  await treatmentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // In a real app, you would submit the treatment to the API
        console.log('Submitting treatment:', {
          patientId: patientInfo.value.id,
          ...treatmentForm.value
        })
        
        ElMessage.success('Treatment submitted successfully')
        resetForm()
      } catch (error) {
        ElMessage.error('Failed to submit treatment')
      }
    }
  })
}

function resetForm() {
  treatmentForm.value = {
    diagnosis: '',
    treatment: '',
    drugs: [{ drug: null, quantity: 1, usage: '' }],
    checks: [{ check: null, note: '' }],
    notes: ''
  }
  
  if (treatmentFormRef.value) {
    treatmentFormRef.value.resetFields()
  }
}
</script>

<style scoped>
.patient-treatment {
  padding: 20px;
}

.patient-card, .treatment-card, .empty-treatment-card {
  margin-bottom: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.select-patient {
  padding: 10px 0;
}

.patient-info {
  margin-top: 10px;
}

.drug-item, .check-item {
  margin-bottom: 10px;
}
</style> 